
import { useState, useEffect } from 'preact/hooks'
import { methodColorMap } from './utils/Common'
import { Layout, Button, Select, Col, Row, Breadcrumb, Spin, Segmented, Tag, List, Flex, theme } from 'antd';
import { CodeOutlined, FormOutlined } from '@ant-design/icons';
import RestfulApi from './services/RestfulApi'
import VirtualList from 'rc-virtual-list'
import ApiExplorer from './components/ApiExplorer'
import type { Endpoint } from './types/Endpoint'
import './app.css'
const { Header, Content, Sider } = Layout
let paths: any = []

export default function App() {
    const [endpoints, setEndpoint] = useState<Endpoint>()
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<string | null>(null)
    const [segmentValue, setSegmentValue] = useState<string>('code')

    useEffect(() => {
        const fetchEndpoints = async () => {
            try {
                const data = new RestfulApi(import.meta.env.VITE_RESTFUL_BASE_URL).get('openapi/config')
                setEndpoint(await data)
            } catch (err) {
                setError(err instanceof Error ? err.message : 'Unknown error')
            } finally {
                setLoading(false)
            }
        }

        fetchEndpoints()
    }, [])

    if (endpoints?.paths) {
        paths = Object.entries(endpoints.paths).map(([path, methods]) => ({
            path,
            ...Object.entries(methods)[0][1]
        }));
    }
    const [selectedKeys, setSelectedKeys] = useState<string>('');
    // const [editMode, setEditMode] = useState(false);
    const flexStyle = {
        width: '100%',
        display: 'flex',
    }
    const layoutStyle = {
        borderRadius: 8,
        overflow: 'hidden',
        width: 'calc(50% - 8px)',
        backgroundColor: '#f5f5f5',
    };
    const siderStyle: React.CSSProperties = {
        textAlign: 'center',
        lineHeight: '120px',
        color: '#fff',
        minWidth: 'calc(15% - 8px)',
        width: '200px',
        backgroundColor: '#ffffff',
    };

    const headerStyle: React.CSSProperties = {
        position: 'relative',
        display: 'flex',
        alignItems: 'center',
        textAlign: 'center',
        color: '#fff',
    };

    const contentStyle: React.CSSProperties = {
        textAlign: 'center',
        minHeight: 120,
        padding: '20px 48px',
        lineHeight: '120px',
        color: '#fff',
    };
    const {
        token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();
    const setBreadcrumb = (path: string) => {
        const segments = path.split('/').filter(Boolean);
        if (segments.length === 0) {
            return [{ key: '', title: '' }];
        }
        return segments.map((segment, index) => ({
            key: segment || 'breadcrumb-' + index,
            title: segment || 'breadcrumb-' + index,
        }));
    };

    return (
        <Flex style={flexStyle} gap="large" wrap>
            <Spin spinning={loading} percent={0} fullscreen />
            <Layout style={layoutStyle}>
                <Header style={headerStyle}>
                    <div className="demo-logo" />
                    <div className="select-version">
                        <Select
                            defaultValue={endpoints?.info.version || '0.0.0'}
                            options={[{ value: '0.0.0', label: 'v0.0.0' }, { value: '1.0.0', label: 'v1.0.0' }, { value: '2.0.0', label: 'v2.0.0' }]}
                        />
                        <Button style={{ marginLeft: 10 }} type="primary" danger>
                            Publish
                        </Button>
                    </div>

                </Header>

                <Layout>
                    <Sider style={siderStyle}>
                        <div className="toolbar">
                            <Button>新增端点</Button>
                            <Button disabled={!selectedKeys}>导出选中</Button>
                        </div>
                        <List bordered={false}
                        >
                            <VirtualList
                                key={selectedKeys}
                                itemKey="path"
                                data={paths}
                                height={400}
                                itemHeight={47}
                            >
                                {(item: any) => (
                                    <List.Item className="list-item" onClick={() => setSelectedKeys(item.path)}>
                                        <span title={item.path} className="truncate">{item.path}</span>
                                        <div className="method-tags">
                                            {Object.keys(item)
                                                .filter(k => typeof item[k] === 'object')
                                                .map(method => (
                                                    <Tag style={{ lineHeight: '9px', fontSize: '8px' }} color={methodColorMap(method)} key={method}>
                                                        {method.toUpperCase()}
                                                    </Tag>
                                                ))}
                                            {/* <Typography.Text mark>sdf</Typography.Text> */}
                                        </div>
                                    </List.Item>
                                )}
                            </VirtualList>
                        </List>
                    </Sider>

                    <Content style={contentStyle}>
                        <div
                            style={{
                                background: colorBgContainer,
                                minHeight: 280,
                                padding: 24,
                                borderRadius: borderRadiusLG,
                            }}
                        >
                            <div className="endpoint-detail">
                                <Breadcrumb
                                    items={setBreadcrumb(selectedKeys)}
                                    style={{ margin: '-10px 0', paddingBottom: '14px' }}
                                />
                                <Row gutter={23} style={{ marginRight: '15px' }}>
                                    <Col span={23}>
                                        <ApiExplorer endpoint={endpoints} path={selectedKeys} segment={segmentValue} />
                                    </Col>
                                    <Col span={1}>
                                        <Segmented style={{ marginLeft: '5px' }}
                                            vertical
                                            size='middle'
                                            shape="round"
                                            onChange={(value) => { setSegmentValue(value) }}
                                            options={[
                                                { value: 'code', icon: <CodeOutlined /> },
                                                { value: 'form', icon: <FormOutlined /> },
                                            ]}
                                        />
                                    </Col>
                                </Row>

                            </div>
                        </div>
                    </Content>

                </Layout>
            </Layout>
        </Flex>
    );
}
